//
//  WindowView.m
//  Test
//
//  Created by jingyao on 2017/12/21.
//  Copyright © 2017年 jingyao. All rights reserved.
//

#import "WindowView.h"

#import "Global.h"
@interface WindowView()
@property (nonatomic, assign) CGFloat beginConstant;
@end

@implementation WindowView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.whiteView.layer.cornerRadius = 14.0f;
    self.whiteView.backgroundColor = [UIColor whiteColor];
    
    self.roundControlImgView.userInteractionEnabled = YES;
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(controlImgMoved:)];
    [self.roundControlImgView addGestureRecognizer:pan];
    
    [self setWindowOn:NO];
}

- (void)controlImgMoved:(UIPanGestureRecognizer *)gesture {
    //NSLog(@"controlImgMoved方法执行了");
    UIImageView *imageView = (UIImageView *)gesture.view;
    
    switch (gesture.state) {
        case UIGestureRecognizerStatePossible:
            break;
            
        case UIGestureRecognizerStateBegan:
            self.beginConstant = self.controlImgViewToFrontLeadingConstraint.constant;
            break;
            
        case UIGestureRecognizerStateChanged:{
            self.textLbl.hidden = YES;
            
            CGPoint touchPoint = [gesture locationInView:self];
            CGFloat moveX = touchPoint.x;
            //NSLog(@"moveX = %f", moveX);
            
            if (moveX < 97) {
                moveX = 97;
            } else if (moveX > 190) {
                moveX = 190;
            }
            
            CGPoint velocityEndDirection = [gesture velocityInView:self];//速率
            if (velocityEndDirection.x > 0) {
                //向右滑动
                self.openingLbl.text = @"Opening...";
                self.controlImgViewToFrontLeadingConstraint.constant = moveX - 99;
            } else if (velocityEndDirection.x < 0) {
                //向左滑动
                self.openingLbl.text = @"Closing...";
                self.controlImgViewToFrontLeadingConstraint.constant = moveX - 99;
            } else {
                //不变
            }
        }
            break;
            
        case UIGestureRecognizerStateEnded: {
            self.textLbl.hidden = NO;
            self.openingLbl.text = @"Slide to control";
            CGPoint touchPoint = [gesture locationInView:self];
            CGFloat moveX = touchPoint.x;
            //NSLog(@"moveX = %f", moveX);
            if (moveX < 97 || moveX > 190) {
                if (self.controlImgViewToFrontLeadingConstraint.constant == self.beginConstant) {
                    //位置没变
                } else {
                    //位置变化了，在这里请求网络接口
                    //NSLog(@"原constant是：%ld", (long)self.beginConstant);
                    if (self.beginConstant < 0) {
                        //开窗
                        self.textLbl.text = @"Slide to close";
                        self.textLbl.textColor = [UIColor whiteColor];
                        self.textLbl.alpha = 0.7f;
                        
                        //[self setAllTenantWindowAndBlindWithValue:@"1"];//tenant账号
                        [self setAll22WindowAndBlindWithValue:@"1"];//fm账号
                    }else {
                        //关窗
                        self.textLbl.text = @"Slide to open";
                        self.textLbl.textColor = [UIColor colorWithRed:55/255.0f green:173/255.0f blue:158/255.0f alpha:1.0f];
                        
                        [self setAllTenantWindowAndBlindWithValue:@"0"];//tenant账号
                        //[self setAll22WindowAndBlindWithValue:@"0"];//fm账号
                    }
                }
            } else {
                //回到原来的位置
                [UIView animateWithDuration:0.3 animations:^{
                    self.controlImgViewToFrontLeadingConstraint.constant = self.beginConstant;
                    [imageView layoutIfNeeded];
                }];
            }
        }
            break;
            
        case UIGestureRecognizerStateCancelled:
            break;
            
        case UIGestureRecognizerStateFailed:
            break;
            
        default:
            break;
    }
}

- (void)setWindowOn:(Boolean)on {
    if (on) {
        self.controlImgViewToFrontLeadingConstraint.constant = 190 - 99.0f;
    } else {
        self.controlImgViewToFrontLeadingConstraint.constant = 97 - 99.0f;
    }
}

#pragma mark - 网络请求接口

- (void)setAllTenantWindowAndBlindWithValue:(NSString *)value {
    NSString *httpStr = [NSString stringWithFormat:@"http://172.105.198.110:8099/api/setAllTenantWindowAndBlind"];
    NSString *str1 = [httpStr stringByAppendingString:@"?value="];
    NSString *str2 = [str1 stringByAppendingString:value];
    NSURL *url = [NSURL URLWithString:str2];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    mRequest.HTTPMethod = @"GET";
    NSString *authValue = [NSString stringWithFormat:@"Bearer %@", [Global getToken]];
    [mRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
    [mRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:
                                      ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                          
                                          if (error) {
                                              NSLog(@"控制所有tenant 账户的窗和窗帘请求error是:%@", error);
                                              return ;
                                          }
                                          
                                          NSLog(@"控制所有tenant 账户的窗和窗帘请求data是%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                          //NSLog(@"response是:%@", response);
                                          
                                          NSError *jsonError;
                                          NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error: &jsonError];
                                          
                                          if (jsonError) {
                                              NSLog(@"控制所有tenant账户的窗和窗帘请求数据转换出错了，jsonError是：%@", jsonError);
                                              return;
                                          }
                                          
                                          NSInteger code = [[dataDic objectForKey:@"code"] integerValue];
                                          if (code == 0) {
                                              //应该是成功
                                              NSArray *resultArray = [dataDic objectForKey:@"result"];
                                              
                                              if (resultArray.count == 0) {
                                                  NSLog(@"result数组返回为空，不能继续");
                                                  return;
                                              }
                                              
                                              NSDictionary *tempDic = resultArray[0];
                                              NSInteger code2 = [[tempDic objectForKey:@"code"] integerValue];
                                              if (code2 == 104) {
                                                  NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)第二个code为104");
                                                  [Global showTextOnly:@"Window locked due to PM2.5"];
                                              }else {
                                                  NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)第二个code不是104，是:%ld", (long)code2);
                                              }
                                          }else {
                                              NSLog(@"控制所有tenant 账户的窗和窗帘请求第一个code不是0，是：%ld", (long)code);
                                          }
                                      }];
    [dataTask resume];
}

- (void)setAll22WindowAndBlindWithValue:(NSString *)value {
    NSString *httpStr = [NSString stringWithFormat:@"http://172.105.198.110:8099/api/setAll22fWindowAndBlind"];
    NSString *str1 = [httpStr stringByAppendingString:@"?value="];
    NSString *str2 = [str1 stringByAppendingString:value];
    NSURL *url = [NSURL URLWithString:str2];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    mRequest.HTTPMethod = @"GET";
    NSString *authValue = [NSString stringWithFormat:@"Bearer %@", [Global getToken]];
    [mRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
    [mRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:
                                      ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                          
                                          if (error) {
                                              NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)error是:%@", error);
                                              return ;
                                          }
                                          
                                          NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)data是%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                          //NSLog(@"response是:%@", response);
                                          
                                          NSError *jsonError;
                                          NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error: &jsonError];
                                          
                                          if (jsonError) {
                                              NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)数据转换出错了，jsonError是：%@", jsonError);
                                              return;
                                          }
                                          
                                          NSInteger code = [[dataDic objectForKey:@"code"] integerValue];
                                          if (code == 0) {
                                              NSArray *resultArray = [dataDic objectForKey:@"result"];
                                              
                                              if (resultArray.count == 0) {
                                                  NSLog(@"result数组返回为空，不能继续");
                                                  return;
                                              }
                                              
                                              NSDictionary *tempDic = resultArray[0];
                                              NSInteger code2 = [[tempDic objectForKey:@"code"] integerValue];
                                              if (code2 == 104) {
                                                  NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)第二个code为104");
                                                  [Global showTextOnly:@"Window locked due to PM2.5"];
                                              }else {
                                                  NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)第二个code不是104，是:%ld", (long)code2);
                                              }
                                          }else {
                                              NSLog(@"控制所有22层的窗和窗帘请求(fm账号使用)第一个code不是0，是：%ld", (long)code);
                                          }
                                      }];
    [dataTask resume];
}
@end
